<!--
 * @Author: Await
 * @Date: 2024-11-07 10:23:38
 * @LastEditors: Await
 * @LastEditTime: 2024-12-25 12:39:53
 * @Description: 请填写简介
-->
<script setup lang="ts">
import { computed, h, onMounted, onUnmounted, ref } from 'vue';
import type {
  DataTableColumns
} from 'naive-ui';
import {
  NAlert,
  NButton,
  NCard,
  NDataTable,
  NForm,
  NFormItem,
  NModal,
  NPopconfirm,
  NSelect,
  NSpace,
  NSwitch,
  NTag,
  useMessage,
} from "naive-ui";
import { $t } from "@/locales";
import {
  addLanguage,
  deleteLanguage,
  fetchLanguageList,
  fetchLanguageOptions,
  updateLanguage
} from "@/service/api";

const message = useMessage();

// 语言选项
const languageOptions = ref<Api.Language.LanguageOption[]>([]);
// 语言配置列表
const languageList = ref<Api.Language.LanguageDto[]>([]);
// 加载状态
const loading = ref(false);

// 表单相关
const showModal = ref(false);
const modalTitle = ref("");
const formRef = ref<typeof NForm | null>(null);
const formValue = ref<Api.Language.LanguageVo>({
  key: "",
  isSkip: false,
});

// 表单验证规则
const rules = {
  key: {
    required: true,
    message: $t("page.translate.form.required.language"),
    trigger: ["blur", "change"],
  },
};

// 表格列定义
const columns = computed<DataTableColumns<Api.Language.LanguageDto>>(() => [
  {
    title: $t("page.translate.table.name"),
    key: "name",
    width: 200,
  },
  {
    title: $t("page.translate.table.key"),
    key: "key",
    width: 150,
  },
  {
    title: $t("page.translate.table.isSkip"),
    key: "isSkip",
    width: 120,
    render: (row) =>
      h(
        NTag,
        {
          type: row.isSkip ? "warning" : "success",
        },
        { default: () => $t(`common.yesOrNo.${row.isSkip ? "yes" : "no"}`) }
      ),
  },
  {
    title: $t("common.action"),
    key: "actions",
    width: 200,
    render: (row) =>
      h(NSpace, null, [
        h(
          NButton,
          {
            size: "small",
            type: "primary",
            secondary: true,
            onClick: () => handleEdit(row),
          },
          { default: () => $t("common.edit") }
        ),
        h(
          NPopconfirm,
          {
            onPositiveClick: () => handleDelete(row.id),
          },
          {
            default: () => $t("common.confirmDelete"),
            trigger: () =>
              h(
                NButton,
                {
                  size: "small",
                  type: "error",
                  secondary: true,
                },
                { default: () => $t("common.delete") }
              ),
          }
        ),
      ]),
  },
]);

// 初始化数据
const retryCount = ref(0);
const maxRetries = 3;

let isUnmounted = false;

onUnmounted(() => {
  isUnmounted = true;
});

async function fetchData() {
  loading.value = true;
  try {
    if (isUnmounted) return;
    const [options, list] = await Promise.all([
      fetchLanguageOptions(),
      fetchLanguageList(),
    ]);
    if (isUnmounted) return;
    languageOptions.value = options.data || [];
    languageList.value = list.data || [];
    retryCount.value = 0;
  } catch {
    if (isUnmounted) return;
    message.error($t("page.translate.message.loadFailed"));
    if (retryCount.value < maxRetries) {
      // retryCount.value++;
      retryCount.value += 1;
      setTimeout(() => fetchData(), 1000 * retryCount.value);
    }
  } finally {
    if (!isUnmounted) {
      loading.value = false;
    }
  }
}

// 添加语言
function handleAdd() {
  modalTitle.value = $t("page.translate.modal.add");
  formValue.value = {
    key: "",
    isSkip: false,
  };
  showModal.value = true;
}

// 编辑语言
function handleEdit(row: Api.Language.LanguageDto) {
  modalTitle.value = $t("page.translate.modal.edit");
  formValue.value = {
    id: row.id,
    key: row.key,
    isSkip: row.isSkip,
  };
  showModal.value = true;
}

// 删除语言
async function handleDelete(id: string) {
  try {
    await deleteLanguage(id);
    message.success($t("page.translate.message.deleteSuccess"));
    await fetchData();
  } catch {
    message.error($t("page.translate.message.deleteFailed"));
  }
}

// 表单提交
async function handleSubmit() {
  try {
    if (!formRef.value) return;
    await formRef.value.validate();
    const api = formValue.value.id ? updateLanguage : addLanguage;
    await api(formValue.value);
    message.success($t("page.translate.message.saveSuccess"));
    showModal.value = false;
    await fetchData();
  } catch (error) {
    if (error instanceof Error) {
      message.error(error.message);
    } else {
      message.error($t("page.translate.message.saveFailed"));
    }
  }
}

onMounted(fetchData);
</script>

<template>
  <div class="p-4">
    <NCard :bordered="false">
      <NSpace vertical :size="16">
        <!-- 页面说明 -->
        <NAlert
          type="info"
          :title="$t('page.translate.tips.title')"
          class="mb-4"
        >
          {{ $t("page.translate.tips.content") }}
        </NAlert>

        <!-- 操作按钮区 -->
        <NSpace justify="end">
          <NButton type="primary" @click="handleAdd">
            {{ $t("common.add") }}
          </NButton>
        </NSpace>

        <!-- 语言配置列表 -->
        <NDataTable
          :loading="loading"
          :columns="columns"
          :data="languageList"
          :bordered="false"
          :pagination="{
            pageSize: 10,
            showSizePicker: true,
            pageSizes: [10, 20, 50],
          }"
          :scroll-x="800"
          :single-line="false"
          striped
        />
      </NSpace>
    </NCard>

    <NModal
      v-model:show="showModal"
      :title="modalTitle"
      preset="dialog"
      :show-icon="false"
    >
      <NForm
        ref="formRef"
        :model="formValue"
        :rules="rules"
        label-placement="left"
        label-width="120"
        require-mark-placement="right-hanging"
      >
        <NFormItem :label="$t('page.translate.form.language')" path="key">
          <NSelect
            v-model:value="formValue.key"
            :options="
              languageOptions.map((item) => ({
                label: item.name,
                value: item.value,
              }))
            "
          />
          <template #feedback>
            {{ $t("page.translate.tips.languageDesc") }}
          </template>
        </NFormItem>

        <NFormItem :label="$t('page.translate.form.isSkip')" path="isSkip">
          <NSwitch v-model:value="formValue.isSkip" />
          <template #feedback>
            {{ $t("page.translate.tips.skipDesc") }}
          </template>
        </NFormItem>
      </NForm>

      <template #action>
        <NSpace justify="end">
          <NButton @click="showModal = false">
            {{ $t("common.cancel") }}
          </NButton>
          <NButton type="primary" @click="handleSubmit">
            {{ $t("common.confirm") }}
          </NButton>
        </NSpace>
      </template>
    </NModal>
  </div>
</template>

<style scoped></style>
